/**   
 *    
 * 项目名称：ShuHuaService   
 * 类名称：CommonUtil   
 * 类描述：Common Util  
 * 创建人：Echo   
 * 创建时间：2014年6月16日 下午5:29:49   
 * 修改人：Echo   
 * 修改时间：2014年6月16日 下午5:29:49   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.lst.dao.ClientNumMapper;
import com.lst.model.MstSchedule;
import com.lst.service.ClientNumService;

/**
 * @ClassName: CommonUtil
 * @Description: Common Util
 * @author Echo
 * @date 2014年6月16日 下午5:29:49
 * 
 */
@SuppressWarnings({ "restriction", "deprecation", "unused" })
public class CommFunUtils {

	private static BASE64Encoder encoder = new BASE64Encoder();
	private static BASE64Decoder decoder = new BASE64Decoder();

	private static Logger logger = Logger.getLogger(CommonUtils.class);

	/**
	 * 
	 * @Title: base64StringToImage
	 * @Description: base64 String To Image
	 * @param @param base64String
	 * @param @param path 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public static void base64StringToImage(String base64String, String path) {
		try {

			String[] base64StrAry = base64String.split(",");

			int base64StrAryLen = base64StrAry.length;

			for (int i = 0; i < base64StrAryLen; i++) {

				byte[] bytes = decoder.decodeBuffer(base64StrAry[i]);

				ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
				BufferedImage bi = ImageIO.read(bais);
				// 可以是jpg,png,gif格式
				File file = new File(path + "_" + (i + 1) + ".jpg");
				// 不管输出什么格式图片，此处不需改动
				ImageIO.write(bi, "jpg", file);
			}
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: base64StringToImage4One
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param base64String
	 * @param @param path 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public static void base64StringToImage4One(String base64String, String path) {
		try {

			byte[] bytes = decoder.decodeBuffer(base64String);

			ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
			BufferedImage bi = ImageIO.read(bais);
			// 可以是jpg,png,gif格式
			File file = new File(path + ".jpg");

			logger.info("File path :" + path + ".jpg");

			// 不管输出什么格式图片，此处不需改动
			ImageIO.write(bi, "jpg", file);

		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: getImageBinary
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param imgFile
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	public static String getImageBinary(String imgFile) {
		File f = new File(imgFile);
		BufferedImage bi;
		try {
			bi = ImageIO.read(f);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(bi, "jpg", baos);
			byte[] bytes = baos.toByteArray();

			return encoder.encodeBuffer(bytes).trim();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 
	 * @Title: makeRandomWithRange
	 * @Description: make Random With Range
	 * @param @param min
	 * @param @param max
	 * @param @return 设定文件
	 * @return int 返回类型
	 * @throws
	 */
	public static int makeRandomWithRange(int min, int max) {
		Random random = new Random();

		int num = random.nextInt(max) % (max - min + 1) + min;

		return num;
	}

	public static List<String> uploadFile(HttpServletRequest request) {

		// String temp = CommonUtils.getTemp_file_path(); // 临时目录
		// 上传文件存放目录
		// String loadpath = CommonUtils.getImg_file_path();

		String temp = CommonUtils.getTemp_file_path_linux(); // 临时目录
		// 上传文件存放目录
		String loadpath = CommonUtils.getImg_file_path_linux();
		System.out.println(loadpath);
		File tempdir = new File(temp);
		if (!tempdir.exists()) {
			tempdir.mkdirs();
		}

		File loadpathdir = new File(loadpath);
		if (!loadpathdir.exists()) {
			loadpathdir.mkdirs();
		}

		System.out.println("loadpath=" + loadpath);
		DiskFileUpload fu = new DiskFileUpload();
		fu.setSizeMax(1 * 1024 * 1024);
		fu.setSizeThreshold(4096);
		fu.setRepositoryPath(temp);

		// 开始读取上传信息
		int index = 0;
		@SuppressWarnings("rawtypes")
		List fileItems = null;

		try {

			fileItems = fu.parseRequest(request);
			System.out.println("fileItems=" + fileItems);
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<String> urls = new ArrayList<String>();

		Iterator<?> iter = fileItems.iterator(); // 依次处理每个上传的文件
		try {

			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息
				if (!item.isFormField()) {
					String name = item.getName();// 获取上传文件名,包括路径
					name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
					long size = item.getSize();
					if ((name == null || name.equals("")) && size == 0)
						continue;

					name = (new Date()).getTime() + ".jpg";
					index++;
					File fNew = new File(loadpath, name);
					item.write(fNew);
					// urls.add(CommCode.S_TP0001 + name);

				}
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
		return urls;
	}

	// 随机生成6位验证码
	public static String getVerCodeWithSixBit() {
		// 产生随机数
		Random random = new Random();
		String code = "";
		for (int i = 0; i < 6; i++) {

			int r = random.nextInt(9);
			code += String.valueOf(r);
		}
		return code;
	}

	/**
	 * 
	 * @Title: parseDatas
	 * @Description: 解析时间区间
	 * @param @param starttime 开始日期
	 * @param @param endtime 结束日期
	 * @param @return
	 * @param @throws ParseException 设定文件
	 * @return List<MstSchedule> 返回日期集
	 */
	public static List<MstSchedule> parseDatas(String starttime, String endtime)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat cn_sdf = new SimpleDateFormat("yyyy年MM月dd日");

		List<MstSchedule> dateList = new ArrayList<MstSchedule>();

		if (starttime.equals(endtime)) {
			Date eDate = sdf.parse(endtime);
			String tempStr = cn_sdf.format(eDate);

			MstSchedule tempSch = new MstSchedule(tempStr);
			dateList.add(tempSch);

			logger.info("decPara idx(i):" + tempStr);
		} else {
			// 获取日期天数
			Date sDate = sdf.parse(starttime);
			Date eDate = sdf.parse(endtime);

			Calendar cal = Calendar.getInstance();
			cal.setTime(sDate);
			long stime_long = cal.getTimeInMillis();
			cal.setTime(eDate);
			long etime_long = cal.getTimeInMillis();
			long days = (etime_long - stime_long) / (1000 * 3600 * 24);

			// 获取日期集合
			Date tempDate = null;
			cal.setTime(sDate);
			MstSchedule tempSch = null;
			// 添加当前日期
			tempDate = cal.getTime();
			tempSch = new MstSchedule(cn_sdf.format(tempDate));
			dateList.add(tempSch);

			for (int i = 0; i < days; i++) {
				cal.add(Calendar.DAY_OF_MONTH, 1);

				tempDate = cal.getTime();
				String tempStr = cn_sdf.format(tempDate);

				tempSch = new MstSchedule(tempStr);
				dateList.add(tempSch);

			}

			// 输出
			for (MstSchedule sch : dateList) {
				logger.info("decPara sch:" + sch.getCodeName());
			}
		}

		return dateList;

	}

	/**
	 * 
	 * @Title: opNum
	 * @Description: 操作统计量
	 * @param @param clientId
	 * @param @param actId
	 * @param @param actType
	 * @param @param numType
	 * @param @param dao
	 * @param @return 设定文件
	 * @return Integer 返回类型
	 */
	public static Integer opNum(Integer clientId, Integer actId,
			Integer actType, Integer numType, ClientNumService clientNumService) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("enabled", true);
		map.put("isdeleted", false);
		map.put("clientid", clientId);
		map.put("actid", actId);
		map.put("acttype", actType);
		map.put("numtype", numType);

		Integer count = clientNumService.queryCountByMap(map);

		if (count == null)
			count = 0;

		return count;
	}

	public static Integer opNum(Integer clientId, Integer actId,
			Integer actType, Integer numType, ClientNumMapper clientNumMapper) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("enabled", true);
		map.put("isdeleted", false);
		map.put("clientid", clientId);
		map.put("actid", actId);
		map.put("acttype", actType);
		map.put("numtype", numType);

		Integer count = clientNumMapper.queryCountByMap(map);

		if (count == null)
			count = 0;

		return count;
	}

	/**
	 * 
	 * @Title: sendSMS
	 * @Description:发送手机短息
	 * @param @param formparams
	 * @param @return 设定文件
	 * @return String 返回类型
	 */
	public static String sendSMS(List<NameValuePair> formparams, String url) {
		CloseableHttpClient httpclient = HttpClients.createDefault();

		// 创建httppost
		HttpPost httppost = new HttpPost(url);

		String result = null;

		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);

			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");

					logger.info("--------------------------------------");
					logger.info("Response content: " + result);
					logger.info("--------------------------------------");
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			logger.error("sendSMS error:", e);
		} catch (UnsupportedEncodingException e1) {
			logger.error("sendSMS error:", e1);
		} catch (IOException e) {
			logger.error("sendSMS error:", e);
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				logger.error("sendSMS error:", e);
			}
		}

		return result;
	}

	/**
	 * 
	 * @Title: parseTimes
	 * @Description: 解析时间区间
	 * @param @param starttime 开始日期
	 * @param @param endtime 结束日期
	 * @param @return
	 * @param @throws ParseException 设定文件
	 * @return List<MstSchedule> 返回日期集
	 */
	public static List<MstSchedule> parseTimes(String starttime, String endtime)
			throws ParseException {
		Date startDate = new Date();
		String day = DateUtil.date2Str(startDate, DateUtil.ALL_DATE_HORIZONTAL);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		SimpleDateFormat cn_sdf = new SimpleDateFormat("HH:mm");

		List<MstSchedule> dateList = new ArrayList<MstSchedule>();

		if (starttime.equals(endtime)) {
			String tempStr = starttime + "-" + endtime;

			MstSchedule tempSch = new MstSchedule(tempStr);
			dateList.add(tempSch);

			logger.info("decPara idx(i):" + tempStr);
		} else {
			// 获取日期天数
			Date sDate = sdf.parse(day + " " + starttime);
			Date eDate = sdf.parse(day + " " + endtime);

			Calendar cal = Calendar.getInstance();
			cal.setTime(sDate);
			long stime_long = cal.getTimeInMillis();
			cal.setTime(eDate);
			long etime_long = cal.getTimeInMillis();
			long hours = (etime_long - stime_long) / (1000 * 3600);

			// 获取日期集合
			Date tempDate = null;
			cal.setTime(sDate);
			MstSchedule tempSch = null;
			/*
			 * // 添加当前日期 tempDate = cal.getTime(); tempSch = new
			 * MstSchedule(cn_sdf.format(tempDate)); dateList.add(tempSch);
			 */
			for (int i = 0; i < hours; i++) {
				cal.add(Calendar.HOUR_OF_DAY, 1);

				tempDate = cal.getTime();
				String tempStr = cn_sdf.format(tempDate);

				tempSch = new MstSchedule(starttime + "-" + tempStr);

				starttime = tempStr;
				dateList.add(tempSch);

			}

			// 输出
			for (MstSchedule sch : dateList) {
				logger.info("decPara sch:" + sch.getCodeName());
			}
		}

		return dateList;

	}

	/**
	 * 
	 * @Title: formatStr
	 * @Description: 格式化字符
	 * @param @param oriStr 原始字符串
	 * @param @param ch 格式化字符
	 * @param @param regex 格式化规则
	 * @param @return 设定文件
	 * @return String 返回类型
	 */
	public static String formatStr(String oriStr, String ch, String regex) {

		String newStr = "";
		try {
			if (!StringUtils.isEmpty(oriStr)) {
				String[] strArr = oriStr.split(regex);

				for (String str : strArr) {
					if (!StringUtils.isEmpty(str)) {
						newStr += ch + str + regex;
					} else {
						newStr += regex;
					}
				}

				if (newStr.length() >= 4) {
					if (newStr.endsWith(regex)) {
						newStr = newStr.substring(0, newStr.length() - 2);
					}
				}

			}

		} catch (Exception e) {
			newStr = "";
			logger.error("formatStr error: ", e);
		}

		return newStr;
	}

	/**
	 * 
	 * @Title: randomStr
	 * @Description: 产生min-max间长度的随机字符串
	 * @param @param min
	 * @param @param max
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public static String randomStr(int min,int max){
		Random random = new Random();
		int len = random.nextInt(max) % (max - min + 1) + min;

		StringBuffer str = new StringBuffer();
		for(int i = 0 ; i < len ;i ++){
			int type = random.nextInt(2);
			if(type == 1){
				char c = (char)(random.nextInt(90) % (90 - 65 + 1) +  65);
				str.append(c);
			} else {
				str.append( random.nextInt(10));
			}
		}

		return str.toString();
	}
	
	
	/**
	 * 从Request对象中获得客户端IP，处理了HTTP代理服务器和Nginx的反向代理截取了ip
	 *
	 * @param request
	 * @return ip
	 */
	public static String getLocalIp(HttpServletRequest request) {
		String remoteAddr = request.getRemoteAddr();
		String forwarded = request.getHeader("X-Forwarded-For");
		String realIp = request.getHeader("X-Real-IP");

		String ip = null;
		if (realIp == null) {
			if (forwarded == null) {
				ip = remoteAddr;
			} else {
				ip = remoteAddr + "/" + forwarded.split(",")[0];
			}
		} else {
			if (realIp.equals(forwarded)) {
				ip = realIp;
			} else {
				if (forwarded != null) {
					forwarded = forwarded.split(",")[0];
				}
				ip = realIp + "/" + forwarded;
			}
		}
		return ip;
	}
}
